//
//  SPAddPartnerViewController.m
//  SuperPatrner
//
//  Created by EvanZ on 15/3/15.
//  Copyright (c) 2015年 EvanZ. All rights reserved.
//

#import "SPAddPartnerViewController.h"
#import "QRCodeGenerator.h"
#import "Define.h"

@interface SPAddPartnerViewController (){
    UIScrollView * m_scrollView;
    UITextView * m_userInfoTextView;
    UIImageView * QRCodeView;
    UIImageView * avatarImageView;
}

@end

@implementation SPAddPartnerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.edgesForExtendedLayout=UIRectEdgeNone;
    self.automaticallyAdjustsScrollViewInsets = NO;
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(loginSuccess) name:NOTI_LOGIN_SUCC object:nil];

    
    m_scrollView = [[UIScrollView alloc]initWithFrame:self.view.frame];
    m_scrollView.showsHorizontalScrollIndicator = NO;
    m_scrollView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:m_scrollView];
    
    avatarImageView = [[UIImageView alloc]initWithFrame:CGRectMake(20, 20, 90, 90)];
    [avatarImageView setImage:[UIImage imageNamed:@"avatar"]];
    [m_scrollView addSubview:avatarImageView];
    
    m_userInfoTextView = [[UITextView alloc]initWithFrame:CGRectMake(self.view.frame.size.width/2-50, 30, self.view.frame.size.width/2+50, 60)];
    [m_userInfoTextView setEditable:NO];
    [m_userInfoTextView setFont:[UIFont systemFontOfSize:15]];
    [m_userInfoTextView setBackgroundColor:[UIColor clearColor]];
    [m_scrollView addSubview:m_userInfoTextView];
    
    UIButton * messageShareButton = [[UIButton alloc]initWithFrame:CGRectMake(100, m_userInfoTextView.frame.origin.y + m_userInfoTextView.frame.size.height + 30, 200, 50)];
    [messageShareButton setCenter:CGPointMake(self.view.center.x, messageShareButton.center.y)];
    [messageShareButton setBackgroundColor:[UIColor grayColor]];
    [messageShareButton setTitle:@"短信发送邀请码" forState:UIControlStateNormal];
    [messageShareButton addTarget:self action:@selector(messageShareButtonListener) forControlEvents:UIControlEventTouchUpInside];
    [m_scrollView addSubview:messageShareButton];
    
    UIButton * mailShareButton = [[UIButton alloc]initWithFrame:CGRectMake(100, messageShareButton.frame.origin.y + messageShareButton.frame.size.height + 25, 200, 50)];
    [mailShareButton setCenter:CGPointMake(self.view.center.x, mailShareButton.center.y)];
    [mailShareButton setBackgroundColor:[UIColor grayColor]];
    [mailShareButton setTitle:@"邮件发送邀请码" forState:UIControlStateNormal];
    [mailShareButton addTarget:self action:@selector(mailShareButtonListener) forControlEvents:UIControlEventTouchUpInside];
    [m_scrollView addSubview:mailShareButton];
    
    UIButton * investmentButton = [[UIButton alloc]initWithFrame:CGRectMake(100, mailShareButton.frame.origin.y + mailShareButton.frame.size.height + 25, 200, 50)];
    [investmentButton setCenter:CGPointMake(self.view.center.x, investmentButton.center.y)];
    [investmentButton setBackgroundColor:[UIColor grayColor]];
    [investmentButton setTitle:@"直接邀请朋友来配资" forState:UIControlStateNormal];
    [investmentButton addTarget:self action:@selector(investmentButtonListener) forControlEvents:UIControlEventTouchUpInside];
    [m_scrollView addSubview:investmentButton];
    
    //QR code
    QRCodeView = [[UIImageView alloc] initWithFrame:CGRectMake(10, investmentButton.frame.origin.y + investmentButton.frame.size.height, 300, 300)];
    [QRCodeView setCenter:CGPointMake(self.view.center.x, QRCodeView.center.y)];
    UIImage * QRImage = [QRCodeGenerator qrImageForString:INVITATION_CODE imageSize:300];
    [QRCodeView setImage:QRImage];
    [m_scrollView addSubview: QRCodeView];
    
    [m_scrollView setContentSize:CGSizeMake(self.view.frame.size.width, QRCodeView.frame.origin.y + QRCodeView.frame.size.height + 160)];
    
    [self loadInfoView];
}

- (void)loadInfoView{
    [m_userInfoTextView setText:[NSString stringWithFormat:@"会员ID：%@ \n昵称：%@ \n邀请码：%@",USER_ID,NICK_NAME,INVITATION_CODE]];
    
    UIImage * QRImage = [QRCodeGenerator qrImageForString:INVITATION_CODE imageSize:300];
    [QRCodeView setImage:QRImage];
}

- (void)loginSuccess{
    [self loadInfoView];
}

#pragma mark - button listeners
- (void)messageShareButtonListener{
    [self showProgressWithText:@"初始化中，请稍后"];
    [self showMessageView];
}

- (void)mailShareButtonListener{
    [self showProgressWithText:@"初始化中，请稍后"];
    [self sendMail];
}

- (void)investmentButtonListener{
    NSURL * url = [NSURL URLWithString:@"https://www.kunzhoudade.com/promote?type=1&u=812345678910"];
    [[UIApplication sharedApplication] openURL:url];
}

#pragma mark - share with message
- (void)showMessageView
{
    
    if( [MFMessageComposeViewController canSendText] ){
        
        MFMessageComposeViewController * controller = [[MFMessageComposeViewController alloc]init]; //autorelease];
        
        controller.recipients = [NSArray arrayWithObject:@""];
        
        //QR code
        UIImage * QRImage = [QRCodeGenerator qrImageForString:INVITATION_CODE imageSize:300];
        NSString * body = [NSString stringWithFormat:@"您的朋友“%@“邀请您成为他的超级合伙人，注册邀请码是：%@，超级合伙人APP下载地址：http://www.baidu.com",NICK_NAME,INVITATION_CODE];
        
        controller.body = body;
        NSData *imageData = UIImagePNGRepresentation(QRImage);
        [controller addAttachmentData:imageData typeIdentifier:@"kUTTypePNG" filename:@"image.png"];
        controller.messageComposeDelegate = self;
        
        [self presentViewController:controller animated:YES completion:nil];
        
        [[[[controller viewControllers] lastObject] navigationItem] setTitle:@"短信分享"];//修改短信界面标题
    }else{
        
        [self alertWithTitle:@"提示信息" msg:@"设备没有短信功能"];
    }
    [self closeProgress];

}


//MFMessageComposeViewControllerDelegate
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result{
    
    [controller dismissViewControllerAnimated:NO completion:nil];
    
    switch ( result ) {
            
        case MessageComposeResultCancelled:
            
            [self alertWithTitle:@"取消发送" msg:@""];
            break;
        case MessageComposeResultFailed:// send failed
            [self alertWithTitle:@"发送失败" msg:@""];
            break;
        case MessageComposeResultSent:
            [self alertWithTitle:@"发送成功" msg:@""];
            break;
        default:
            break;
    }
}

#pragma mark - share with mail
- (void)sendMail
{
    Class mailClass = (NSClassFromString(@"MFMailComposeViewController"));
    if (!mailClass) {
        [self alertWithTitle:@"当前系统版本不支持应用内发送邮件功能，您可以使用mailto方法代替" msg:@""];
        return;
    }
    if (![mailClass canSendMail]) {
        [self alertWithTitle:@"用户没有设置邮件账户" msg:@""];
        return;
    }
    [self displayMailPicker];
}

//调出邮件发送窗口
- (void)displayMailPicker
{
    MFMailComposeViewController *mailPicker = [[MFMailComposeViewController alloc] init];
    mailPicker.mailComposeDelegate = self;
    
    //QR code
    //UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 50, 300, 300)];
    UIImage * QRImage = [QRCodeGenerator qrImageForString:INVITATION_CODE imageSize:300];
    //[self.view addSubview: imageView];
    //设置主题
    [mailPicker setSubject: @"邀请码"];
    //添加收件人
    NSArray *toRecipients = [NSArray arrayWithObject: @""];
    [mailPicker setToRecipients: toRecipients];
    //添加抄送
    NSArray *ccRecipients = [NSArray arrayWithObjects:@"", nil];
    //[mailPicker setCcRecipients:ccRecipients];
    //添加密送
    NSArray *bccRecipients = [NSArray arrayWithObjects:@"fourth@example.com", nil];
    //[mailPicker setBccRecipients:bccRecipients];

    // 添加一张图片
    NSData *imageData = UIImagePNGRepresentation(QRImage);            // png
    [mailPicker addAttachmentData: imageData mimeType: @"" fileName: @"image.png"];

    [mailPicker setMessageBody:INVITATION_CODE isHTML:NO];

    [self presentViewController:mailPicker animated:YES completion:nil];
    
    [self closeProgress];
}

#pragma mark - 实现 MFMailComposeViewControllerDelegate
- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{    //关闭邮件发送窗口
    [self dismissViewControllerAnimated:YES completion:nil];
    NSString *msg;
    switch (result) {
        case MFMailComposeResultCancelled:
            msg = @"取消编辑邮件";
            break;
        case MFMailComposeResultSaved:
            msg = @"成功保存邮件";
            break;
        case MFMailComposeResultSent:
            msg = @"邮件发送成功";
            break;
        case MFMailComposeResultFailed:
            msg = @"发送邮件失败";
            break;
        default:
            msg = @"";
            break;
    }
    [self alertWithTitle:msg msg:@""];
}



- (void) alertWithTitle:(NSString *)title msg:(NSString *)msg {
    
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
                                                    message:msg
                                                   delegate:self
                                          cancelButtonTitle:nil
                                          otherButtonTitles:@"确定", nil];
    
    [alert show];
    
}

@end
